'use strict';

function tokenAuthentication() {
	return async (ctx, next) => {
		const config = ctx.app.config;
		let authorization = ctx.request.header['authorization'];
		if (!authorization) return ctx.body = { code: -1, message: '缺少token令牌!', data: {} }
		let token = ctx.request.header['authorization'].replace("Bearer ", ''); //获取头部token信息
		if (token) {
			let overdue = true;
			// 解析token生成用户信息
			try {
				const userInfo = ctx.app.jwt.verify(token, config.jwt.secret);
				ctx.userInfo = userInfo;
			} catch (error) {
				overdue = false;
				ctx.status = 401;
				return ctx.body = { code: -1, message: 'token令牌已过期!', data: {} }
			}
			if (overdue) await next()
		} else {
			return ctx.body = { code: -1, message: '缺少token令牌!', data: {} }
		}
	};
}

module.exports = tokenAuthentication;